package TCPEcho;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPEchoSever1 {
    private ServerSocket socket = null;

    public  TCPEchoSever1(int port) throws IOException {
        socket = new ServerSocket(port);
    }
    public void start() throws IOException {
        ExecutorService pool = Executors.newCachedThreadPool();
        System.out.println("服务器启动！");
        while(true){
           Socket clineSocket =  socket.accept();
           pool.submit(new Runnable() {
               @Override
               public void run() {
                   try {
                       processConetion(clineSocket);
                   } catch (IOException e) {
                       throw new RuntimeException(e);
                   };
               }
           });
        }
    }

    private void processConetion(Socket clineSocket) throws IOException {
        System.out.printf("客户端已上线：[%s:%d]\n",clineSocket.getInetAddress(),clineSocket.getPort());
        try(InputStream inputStream = clineSocket.getInputStream();
            OutputStream outputStream = clineSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("客户端已下线：[%s:%d]\n",clineSocket.getInetAddress(),clineSocket.getPort());
                    break;
                }
                //读取客户端发送过来的请求
                String request = scanner.next();
                //根据请求构造响应
                String response = process(request);
                //返回响应给服务器
                writer.println(response);
                writer.flush();
                //打印日志
                System.out.printf("[%s:%d] req:%s resp:%s\n",clineSocket.getInetAddress(),clineSocket.getPort(),request,response);
            }
        }
    }

    private String process(String request) {
        return  request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoSever1 tcpEchoSever1 = new TCPEchoSever1(4090);
        tcpEchoSever1.start();
    }
}
